package com.wl.boot.batch.util;

import com.wl.boot.batch.bean.entity.CommonExcelConfig;
import com.wl.boot.batch.bean.entity.CommonExcelPageField;
import com.wl.boot.batch.mapper.excelMapper;
import com.wl.boot.batch.service.ExcelAsyncService;

import java.util.List;

/**
 * @author wanglu
 * @date 2021-08-18 22:52
 */
public class MyTask implements Runnable{
    private excelMapper dao;
    private List<Object> list;
    private CommonExcelConfig ec;
    private List<CommonExcelPageField> epf;

    public MyTask(excelMapper dao, List<Object> list, CommonExcelConfig ec, List<CommonExcelPageField> epf) {
        this.list = list;
        this.ec = ec;
        this.epf = epf;

    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */

    @Override
    public void run() {
        this.dao = MyBatisUtils.getSession().getMapper(excelMapper.class);
        if (list.size() <= 3000) {
            try {
                dao.batchTargetTable(ec.getTargetTable(), list, epf);
            }catch (Exception e){
                e.printStackTrace();
            }
        } else {
            int length = list.size();
            // 计算可以分成多少组
            int num = (length + 3000 - 1) / 3000;
            for (int i = 0; i < num; i++) {
                // 开始位置
                int fromIndex = i * 3000;
                // 结束位置
                int toIndex = (i + 1) * 3000 < length ? (i + 1) * 3000 : length;
                try {
                    dao.batchTargetTable(ec.getTargetTable(), list.subList(fromIndex, toIndex), epf);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
